﻿// Author: AustralTek 
// Create date: 2010/05/04
// http://www.australtek.com
// Copyright: 2009 - 2010

(function () {
    try {
        function _ScopePicker(obj, options) {
            try {
                /*--------------------------*/
                /*----Private properties----*/
                /*--------------------------*/
                var containerAux;
                var container;
                var calendarPicker = {
                    container: null
                    , obj: null
                };
                var timePicker = {
                    container: null
                    , obj: null
                };
                var ddpScopePicker = {
                    container: null
                    , obj: null
                };
                var buttons = {
                    bwButton: null
                    , fwButton: null
                }
                var privateParameters = {
                    defaultDateTime: null
                    , calendarPickerOptions: null
                    , timePickerOptions: null
                    , dspParameters: { // ddp scope picker Parameters
                        dspOptions: null
                        , defaultSelectedOptionsIndex: null
                        , events: {
                            onChange: function () { }
                        }
                    }
                    //buttonsOptions
                    , buttonsOptions: {
                        enabled: null
                    }
                    //events
                    , events: {
                        onComplete: function () { }
                        , onChange: function () { }
                        , onError: function () { }
                    }
                };

                /* Sets and Overrides certains properties.*/
                function _initialize(obj, options) {
                    try {
                        containerAux = obj;
                        container = null;
                        calendarPicker.container = null;
                        calendarPicker.obj = null;
                        timePicker.container = null;
                        timePicker.obj = null;
                        ddpScopePicker.container = null;
                        ddpScopePicker.obj = null;
                        buttons.bwButton = null;
                        buttons.fwButton = null;

                        privateParameters = new PrivateParameters(options);
                        /*----------------------------*/
                        /* calendar picker parameters */
                        /*----------------------------*/
                        privateParameters.CalendarPickerOptions = privateParameters.CalendarPickerOptions || new Object();
                        privateParameters.CalendarPickerOptions.Events = privateParameters.CalendarPickerOptions.Events || new Object();
                        if (privateParameters.CalendarPickerOptions.Events.onChange) {
                            var tempFunction = privateParameters.CalendarPickerOptions.Events.onChange;
                            privateParameters.CalendarPickerOptions.Events.onChange = function () {
                                tempFunction();
                                privateParameters.Events.onChange();
                            }
                        }
                        else
                            privateParameters.CalendarPickerOptions.Events.onChange = privateParameters.Events.onChange;
                        if (privateParameters.CalendarPickerOptions.Events.onError) {
                            var tempFunction2 = privateParameters.CalendarPickerOptions.Events.onError;
                            privateParameters.CalendarPickerOptions.Events.onError = function () {
                                tempFunction2();
                                privateParameters.Events.onError();
                            }
                        }
                        else
                            privateParameters.CalendarPickerOptions.Events.onError = privateParameters.Events.onError;
                        /*----------------------------*/
                        /* time picker parameters */
                        /*----------------------------*/
                        privateParameters.TimePickerOptions = privateParameters.TimePickerOptions || new Object();
                        privateParameters.TimePickerOptions.Events = privateParameters.TimePickerOptions.Events || new Object();
                        if (privateParameters.TimePickerOptions.Events.onChange) {
                            var tempFunction3 = privateParameters.TimePickerOptions.Events.onChange;
                            privateParameters.TimePickerOptions.Events.onChange = function () {
                                tempFunction3();
                                privateParameters.Events.onChange();
                            }
                        }
                        else
                            privateParameters.TimePickerOptions.Events.onChange = privateParameters.Events.onChange;
                        if (privateParameters.TimePickerOptions.Events.onError) {
                            var tempFunction4 = privateParameters.TimePickerOptions.Events.onError;
                            privateParameters.TimePickerOptions.Events.onError = function () {
                                tempFunction4();
                                privateParameters.Events.onError();
                            }
                        }
                        else
                            privateParameters.TimePickerOptions.Events.onError = privateParameters.Events.onError;
                        /*----------------------------*/
                        /* ddp scope picker parameters */
                        /*----------------------------*/
                        privateParameters.DDPScopePickerOptions = privateParameters.DDPScopePickerOptions || new Object();
                        privateParameters.DDPScopePickerOptions.DSPOptions = privateParameters.DDPScopePickerOptions.DSPOptions || new Array();
                        privateParameters.DDPScopePickerOptions.DefaultSelectedOptionsIndex = privateParameters.DDPScopePickerOptions.DefaultSelectedOptionsIndex || 0;
                        privateParameters.DDPScopePickerOptions.DSPOptions = null;
                        if (privateParameters.DDPScopePickerOptions.Events.onChange) {
                            var tempFunction5 = privateParameters.DDPScopePickerOptions.Events.onChange;
                            privateParameters.DDPScopePickerOptions.Events.onChange = function () {
                                tempFunction5();
                                privateParameters.Events.onChange();
                            }
                        }
                        /*----------------------------*/
                        /* buttons picker parameters */
                        /*----------------------------*/
                        privateParameters.ButtonsOptions = privateParameters.ButtonsOptions || new Object();
                        privateParameters.ButtonsOptions.Enabled = (privateParameters.ButtonsOptions.Enabled === false) ? false : true;
                        /*----------------------------*/
                        /* general parameters */
                        /*----------------------------*/
                        var autoDateTime = getItem('dateTime'); // auto start
                        privateParameters.DefaultDateTime = (autoDateTime)
                                                    ? new Date(autoDateTime)
                                                    : ((privateParameters.DefaultDateTime)
                                                        ? new Date(privateParameters.DefaultDateTime)
                                                        : null
                                                    );
                    }
                    catch (Error) { privateParameters.Events.onError(Error); }
                }

                function _redraw() {
                    try {
                        container = document.createElement('div');
                        container.className = 'ScopePickerContainers';
                        containerAux.appendChild(container);

                        /*-------------------------*/
                        // Instance CalendarPicker
                        /*-------------------------*/
                        calendarPicker.container = document.createElement('div');
                        calendarPicker.container.className = 'CalendarPickerGlobalContainers';
                        container.appendChild(calendarPicker.container);
                        calendarPicker.obj = new CalendarPicker(calendarPicker.container, privateParameters.CalendarPickerOptions);
                        /*-------------------------*/
                        /*-------------------------*/
                        // Instance TimePicker
                        /*-------------------------*/
                        timePicker.container = document.createElement('div');
                        timePicker.container.className = 'TimePickerGlobalContainers';
                        container.appendChild(timePicker.container);
                        timePicker.obj = new TimePicker(timePicker.container, privateParameters.TimePickerOptions);
                        /*-------------------------*/
                        /*-------------------------*/
                        // Instance ddp scope picker
                        /*-------------------------*/
                        ddpScopePicker.container = document.createElement('div');
                        ddpScopePicker.container.className = 'DScopePickerGlobalContainers';
                        container.appendChild(ddpScopePicker.container);

                        ddpScopePicker.obj = document.createElement('select');
                        ddpScopePicker.obj.className = 'DScopePickerContainers';
                        ddpScopePicker.container.appendChild(ddpScopePicker.obj);

                        if (privateParameters.DDPScopePickerOptions.DSPOptions) {
                            for (var iOption = 0; iOption < privateParameters.DDPScopePickerOptions.DSPOptions; iOption++) {
                                var dspOptionData = privateParameters.DDPScopePickerOptions.DSPOptions[iOption];
                                var dspOption = document.createElement('option');
                                dspOption.innerHTML = dspOptionData.title;
                                dspOption.value = dspOptionData.value; // in minutes
                                ddpScopePicker.obj.appendChild(dspOption);
                            }
                        }
                        else {
                            var dspOptionsList = new Array();
                            dspOptionsList.push({ innerHTML: '1 minute', value: 1 });
                            dspOptionsList.push({ innerHTML: '15 minutes', value: 15 });
                            dspOptionsList.push({ innerHTML: '30 minutes', value: 30 });
                            dspOptionsList.push({ innerHTML: '1 hour', value: 60 });
                            dspOptionsList.push({ innerHTML: '6 hours', value: 360 });
                            dspOptionsList.push({ innerHTML: '12 hours', value: 720 });
                            dspOptionsList.push({ innerHTML: '1 day', value: 1440 });
                            dspOptionsList.push({ innerHTML: '1 week', value: 10080 });
                            dspOptionsList.push({ innerHTML: '1 month', value: 43200 });
                            for (var iOption = 0; iOption < dspOptionsList.length; iOption++) {
                                var dspOption = document.createElement('option');
                                dspOption.innerHTML = dspOptionsList[iOption].innerHTML;
                                dspOption.value = dspOptionsList[iOption].value;
                                ddpScopePicker.obj.appendChild(dspOption);
                            }
                        }

                        ddpScopePicker.obj.selectedIndex = privateParameters.DDPScopePickerOptions.DefaultSelectedOptionsIndex || 0;
                        addEventHandler(ddpScopePicker.obj, 'onchange', _dspChange);
                        /*-------------------------*/
                        /*-------------------------*/
                        // Buttons
                        /*-------------------------*/
                        if (privateParameters.ButtonsOptions.Enabled) {
                            var bwButtonContainer = document.createElement('div');
                            bwButtonContainer.className = 'ButtonContainers';
                            container.insertBefore(bwButtonContainer, container.childNodes[0]);
                            buttons.bwButton = document.createElement('input');
                            buttons.bwButton.className = 'LeftButtons';
                            buttons.bwButton.type = 'button';
                            buttons.bwButton.direction = -1;
                            bwButtonContainer.appendChild(buttons.bwButton);
                            addEventHandler(buttons.bwButton, 'onclick', _buttonsClick);

                            var fwButtonContainer = document.createElement('div');
                            fwButtonContainer.className = 'ButtonContainers';
                            container.appendChild(fwButtonContainer);
                            buttons.fwButton = document.createElement('input');
                            buttons.fwButton.className = 'RightButtons';
                            buttons.fwButton.type = 'button';
                            buttons.fwButton.direction = 1;
                            fwButtonContainer.appendChild(buttons.fwButton);
                            addEventHandler(buttons.fwButton, 'onclick', _buttonsClick);
                            //                            }
                        }
                        /*-------------------------*/

                        // Set default datetime if is not null
                        if (privateParameters.DefaultDateTime) {
                            calendarPicker.obj.SetValue(privateParameters.DefaultDateTime);
                            timePicker.obj.SetValue(privateParameters.DefaultDateTime);
                        }
                    }
                    catch (Error) { privateParameters.Events.onError(Error); }
                }

                /*-----------------------*/
                /*----Private methods----*/
                /*-----------------------*/

                function _moveScope(direction) {
                    try {
                        // Get new datetime
                        var scopeMove = (ddpScopePicker.obj.value * 60000) / 2;
                        var selectedDateTime = new Date(calendarPicker.obj.GetResults().GetQueryParameters()[0].value + ' ' + timePicker.obj.GetResults().GetQueryParameters()[0].value).getTime();
                        var newDateTime = new Date(selectedDateTime + scopeMove * direction);

                        // Refresh Pickers
                        var valid = false;
                        calendarPicker.obj.SetValue(newDateTime);
                        timePicker.obj.SetValue(newDateTime);

                        privateParameters.Events.onChange();
                    }
                    catch (Error) { privateParameters.Events.onError(Error); }
                }

                function _setDDPScopePickerOption(newIndex) {
                    try {
                        ddpScopePicker.obj.selectedIndex = newIndex;
                    }
                    catch (Error) { privateParameters.Events.onError(Error); }
                }

                function _getDDPScopePickerValue() {
                    try {
                        return ddpScopePicker.obj.value;
                    }
                    catch (Error) { privateParameters.Events.onError(Error); }
                }

                function _setValue(newValue) {
                    try {
                        if (newValue instanceof Date) {
                            calendarPicker.obj.SetValue(newDateTime);
                            if (privateParameters.TimePickerOptions.Enabled)
                                timePicker.obj.SetValue(newDateTime);
                        }
                        else {
                            if (newValue.target.toUpperCase() == 'CP') // calendar picker
                                calendarPicker.obj.SetValue(newValue.value);
                            else if (newValue.target.toUpperCase() == 'TP') // time picker
                                timePicker.obj.SetValue(newValue.value);
                            else if (newValue.target.toUpperCase() == 'DSP') // ddp scope picker
                                ddpScopePicker.obj.selectedIndex = newValue.value;
                        }
                    }
                    catch (Error) { privateParameters.Events.onError(Error); }
                }

                function _getResults(options) {
                    var ret = null;
                    try {
                        options = options || { DBEngine: 'SQLServer', paramsWishList: null }; //DBEngine = SQL Server by default.
                        options.DBEngine = options.DBEngine || 'SQLServer';

                        var DBType = 4; //Type = DATETIME (SQLServer type by default)

                        switch (options.DBEngine.toUpperCase()) {
                            case 'SQLSERVER': break;
                            case 'ORACLE': DBType = 106; break; //Type = DATE
                            default: throw Error;
                        };

                        ret = new QueryParameters({ DBEngine: options.DBEngine });

                        var selectedDatetime = new Date(calendarPicker.obj.GetResults().GetQueryParameters()[0].value + ' ' + timePicker.obj.GetResults().GetQueryParameters()[0].value).getTime();
                        var halfScope = (parseInt(ddpScopePicker.obj.value) * 60000) / 2;
                        var startScope = new Date(selectedDatetime - halfScope);
                        var endScope = new Date(selectedDatetime + halfScope);

                        var startHours = startScope.getHours();
                        startHours = (startHours < 10) ? '0' + startHours : startHours;
                        var startMinutes = startScope.getMinutes();
                        startMinutes = (startMinutes < 10) ? '0' + startMinutes : startMinutes;
                        var startSeconds = startScope.getSeconds();
                        startSeconds = (startSeconds < 10) ? '0' + startSeconds : startSeconds;
                        var endHours = endScope.getHours();
                        endHours = (endHours < 10) ? '0' + endHours : endHours;
                        var endMinutes = endScope.getMinutes();
                        endMinutes = (endMinutes < 10) ? '0' + endMinutes : endMinutes;
                        var endSeconds = endScope.getSeconds();
                        endSeconds = (endSeconds < 10) ? '0' + endSeconds : endSeconds;

                        var startScopeString = startScope.getFullYear() + '/' + (startScope.getMonth() + 1) + '/' + startScope.getDate() + ' ' + startHours + ':' + startMinutes + ':' + startSeconds;
                        var endScopeString = endScope.getFullYear() + '/' + (endScope.getMonth() + 1) + '/' + endScope.getDate() + ' ' + endHours + ':' + endMinutes + ':' + endSeconds;

                        if (options.paramsWishList) {
                            for (var iParamWish = 0; iParamWish < 2; iParamWish++) {
                                if (options.paramsWishList[iParamWish] == 'StartScope')
                                    ret.Add('StartScope', DBType, startScopeString);
                                else if (options.paramsWishList[iParamWish] == 'EndScope')
                                    ret.Add('EndScope', DBType, endScopeString);
                            }
                        }
                        else {
                            ret.Add('StartScope', DBType, startScopeString);
                            ret.Add('EndScope', DBType, endScopeString);
                        }
                    }
                    catch (Error) { privateParameters.Events.onError(Error); }
                    return ret;
                }

                /*--------------------*/
                /* ----- Events ----- */
                /*--------------------*/

                function _buttonsClick(e) {
                    try {
                        var button = e.srcElement || e.target;
                        _moveScope(button.direction);
                    }
                    catch (Error) { privateParameters.Events.onError(Error); }
                }

                function _dspChange(e) {
                    try {
                        privateParameters.DDPScopePickerOptions.Events.onChange();
                    }
                    catch (Error) { privateParameters.Events.onError(Error); }
                }

                /*----------------*/
                /*-----Public-----*/
                /*----------------*/

                /*----------------------*/
                /*--------Methods-------*/
                /*----------------------*/
                this.GetResults = function (options) {
                    return _getResults(options);
                };
                this.SetValue = function (newValue) {
                    _setValue(newValue);
                };
                this.SetCalendarPickerValue = function (newDate) {
                    calendarPicker.obj.SetValue(newDate);
                }
                this.GetCalendarPickerResults = function () {
                    return calendarPicker.obj.GetResults();
                }
                this.SetTimePickerValue = function (newTime) {
                    timePicker.obj.SetValue(newTime);
                }
                this.GetTimePickerResults = function () {
                    return timePicker.obj.GetResults();
                }
                this.SetDDPScopePickerOption = function (newIndex) {
                    _setDDPScopePickerOption(newIndex);
                }
                this.GetDDPScopePickerValue = function () {
                    return _getDDPScopePickerValue();
                }

                /*-----------------------------------------------------------------------*/
                /*-----------------------------------------------------------------------*/
                /*-----------------------------------------------------------------------*/
                try {
                    /* Sets properties.*/
                    _initialize(obj, options);
                    _redraw();
                }
                catch (Error) { privateParameters.Events.onError(Error); }
                /*-----------------------------------------------------------------------*/
                /*-----------------------------------------------------------------------*/
                /*-----------------------------------------------------------------------*/
            }
            catch (Error) { window.status = Error.Message; }
        }

        window.ScopePicker = function (obj, instanceOptions) { return new _ScopePicker(obj, instanceOptions); };
    }
    catch (Error) { window.status = Error.Message; }
})();